// 图片优化工具
export const imageOptimizer = {
  // 预加载图片
  preloadImage: (src: string): Promise<void> => {
    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = () => resolve()
      img.onerror = reject
      img.src = src
    })
  },

  // 批量预加载
  preloadImages: async (srcs: string[]): Promise<void> => {
    const promises = srcs.map(src => imageOptimizer.preloadImage(src))
    await Promise.all(promises)
  },

  // 获取优化后的图片URL
  getOptimizedUrl: (url: string, width: number, height?: number): string => {
    const urlObj = new URL(url)
    
    // 添加优化参数
    urlObj.searchParams.set('w', width.toString())
    if (height) {
      urlObj.searchParams.set('h', height.toString())
    }
    urlObj.searchParams.set('fit', 'crop')
    urlObj.searchParams.set('q', '80')
    urlObj.searchParams.set('auto', 'format')
    
    return urlObj.toString()
  },

  // 懒加载配置
  lazyLoadConfig: {
    rootMargin: '50px',
    threshold: 0.01,
  },
}

// 性能监控
export const performanceMonitor = {
  mark: (name: string) => {
    if (typeof window !== 'undefined' && window.performance) {
      window.performance.mark(name)
    }
  },

  measure: (name: string, start: string, end: string) => {
    if (typeof window !== 'undefined' && window.performance) {
      window.performance.measure(name, start, end)
    }
  },

  getEntries: () => {
    if (typeof window !== 'undefined' && window.performance) {
      return window.performance.getEntriesByType('measure')
    }
    return []
  },
}
